package algorithm.leetcode.online.q6nnnnzigzag;

/**
 * Created by IntelliJ IDEA.
 * User: jwang
 * Date: Jul 9, 2013
 * Time: 5:37:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class Zigzag {
  public static void main(String[] args){
    String a = "PAYPALISHIRING";
    System.out.print(convert(a,3));
  }
  private static String convert(String text, int nRows){
    String result = "";
    int len = text.length();
    if(nRows == 1 || len == 1) return text;
    int middlenum = nRows - 2;
    int nCols = (len % (nRows+middlenum) > 0) ? (len/(nRows+middlenum)) *2 + 1 : (len/(nRows+middlenum)) *2;
    char[][] chars = new char[nCols][];
    char[][] squareChars = new char[nCols][] ;
    int start =0, end = nRows;


    for(int i = 0; i < nCols; i++){
      if(i < nCols-1){
        chars[i] = text.substring(start,end).toCharArray();
      }else{
        chars[i] = text.substring(start).toCharArray();
      }
      squareChars[i] = new char[nRows];
      if(i%2 == 0){
        start += nRows;
        end = start + middlenum;
        for(int j = 0; j < nRows; j++){
          squareChars[i][j] = j < chars[i].length? chars[i][j] : '\u0000';
        }


      }else{
        start += middlenum;
        end = start + nRows;
        squareChars[i][0] = '\u0000';
        for(int j = 1; j < nRows-1; j++){
          squareChars[i][j] = (j - 1) < chars[i].length? chars[i][j-1] : '\u0000';
        }
      }
    }

    for(int i = 0; i < nRows; i++){
      for(int j = 0; j < nCols; j++){
        if(squareChars[j][i] != '\u0000'){
         result += squareChars[j][i];
        }

      }
    }
//      for(int j = 0; j < arrayChars.length; j++){
//        arrayChars[j][i] = text.charAt(k);
//        k++;
//      }
    return result;
  }
}

